package com.zsr.chapter05.servlet;

import com.zsr.chapter05.bean.Book;
import com.zsr.chapter05.bean.BookDB;

import javax.servlet.ServletException;
import javax.servlet.http.*;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author zsr
 * @Description 实现加入购物车
 * @Date 2021/4/22 10:25
 */
public class PurchaseServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String id=request.getParameter("id");
        if(id==null){
            //如果id为空，重定向到ListBookServlet
            response.sendRedirect("/javaweb_task_demo/listBookServlet");
        }
        Book book = BookDB.getBook(id);
        //创建或者获得用户的Session对象
        HttpSession session = request.getSession();
        //从session中获取用户的购物车对象
        List<Book> cart =(List) session.getAttribute("cart");
        if(cart==null){
            //首次购买，为用户创建一个购物车（List集合）
            cart =new ArrayList<Book>();
            //将购物车存入session对象
            session.setAttribute("cart",cart);
        }
        //将商品放入购物车
        cart.add(book);
        //图书列表中删除图书
        BookDB.deleteBook(id);
        //创建Cookie存放session的标识号
        Cookie cookie=new Cookie("JSESSIONID",session.getId());
        cookie.setMaxAge(60* 30);
        cookie.setPath("/javaweb_task_demo");
        response.addCookie(cookie);
        response.sendRedirect("/javaweb_task_demo/cartServlet");
    }
}
